var poly;
var map;
var index = -1;
var info_windows = {};
var markers = {};

window.onload = function() { initialize(); }

function popup(new_index) {
    if (index >= 0)
        info_windows[index].close();
    else if (map.getZoom() < 14)
        map.setZoom(14);
    info_windows[new_index].open(map, markers[new_index]);
    index = new_index;
    update_opacity();
}

function addWaypoint(i, data, type) {
    var image;
    var contentString = '';
    var prefix = '<div id="map_popup">';
    var postfix = '</div>';
    if (type == "start") {
        image = new google.maps.MarkerImage('/static/img/icon_start.png',
            new google.maps.Size(25, 34),
            new google.maps.Point(0, 0),
            new google.maps.Point(12, 30));
        contentString = prefix + '<p class="start">行程起点</p>' + postfix;
    } else if (type == "photo") {
        image = new google.maps.MarkerImage('/static/img/icon_photo.png',
            new google.maps.Size(25, 34),
            new google.maps.Point(0, 0),
            new google.maps.Point(12, 30));
        contentString = prefix + '<a href="#wp' + data[2] + '"><img width="200" height="150" src="' + data[1] + '" /></a>' + postfix;
        $('#wp' + data[2]).attr('lat', data[0].lat())
        $('#wp' + data[2]).attr('lng', data[0].lng())
    } else if (type == "text") {
        image = new google.maps.MarkerImage('/static/img/icon_text.png',
            new google.maps.Size(25, 34),
            new google.maps.Point(0, 0),
            new google.maps.Point(12, 30));
        contentString = prefix + '<a class="text" href="#wp' + data[2] + '">"' + data[1] + '"</a>' + postfix;
        $('#wp' + data[2]).attr('lat', data[0].lat())
        $('#wp' + data[2]).attr('lng', data[0].lng())
    }

    var marker = new google.maps.Marker({
        position: data[0],
        map: map,
        icon: image
    });
    markers[i] = marker;

    var infowindow = new google.maps.InfoWindow({
        content: contentString
    });
    info_windows[i] = infowindow;

    google.maps.event.addListener(marker, 'click', function() {
        popup(i);
    });
}

function getData(point) {
    var items = point.children();
    var lat = parseFloat($(items[0]).text());
    var lon = parseFloat($(items[1]).text());
    var content = $(items[2]).text();
    var wp_id = null;
    if (items.length > 3)
        wp_id = $(items[3]).text();
    return [new google.maps.LatLng(lat, lon), content, wp_id];
}

function initialize() {
    var options = {
        zoom: 14,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("trip_map"), options);

    var points = $('#map_data').children();
    var coordinates = [];
    var latlngbounds = new google.maps.LatLngBounds();
    for (var i = 0; i < points.length; i++) {
        var point = $(points[i]);
        var type = point.attr('class');
        data = getData(point);
        if (type != 'track')
            addWaypoint(i, data, type);
        coordinates.push(data[0]);
        latlngbounds.extend(data[0]);
    }

    var path = new google.maps.Polyline({
        path: coordinates,
        strokeColor: "#0695f8",
        strokeOpacity: 1.0,
        strokeWeight: 4
    });

    if (points.length == 1)
        map.setCenter(coordinates[0]);
    else {
        map.fitBounds(latlngbounds);
        path.setMap(map);
    }
}

function update_opacity() {
    var waypoints = $('#map_data').children('[class!="track"]');
    var first_index = waypoints.first().index();
    var last_index = waypoints.last().index();
    if (index == first_index)
        $('#map_controller a.left').css('opacity', 0.3);
    else
        $('#map_controller a.left').css('opacity', 1);
    if (index == last_index)
        $('#map_controller a.right').css('opacity', 0.3);
    else
        $('#map_controller a.right').css('opacity', 1);
}

function move_to_next() {
    if ($(this).css('opacity') - 0.3 < 0.001)
        return false;

    if (index >= 0) {
        current_point = $('#map_data li:nth-child(' + (index + 1) + ')').nextAll('li[class!="track"]').first();
    } else {
        current_point = $('#map_data').children('[class!="track"]').first();
    }

    new_index = current_point.index();
    latlon = getData(current_point)[0];
    map.panTo(latlon);
    popup(new_index);
    return false;
}

function move_to_prev() {
    if ($(this).css('opacity') - 0.3 < 0.001)
        return false;

    current_point = $('#map_data li:nth-child(' + (index + 1) + ')').prevAll('[class!="track"]').first();
    new_index = current_point.index();
    latlon = getData(current_point)[0];
    map.panTo(latlon);
    popup(new_index);
    return false;
}

$(function() {

    $('#bookmark').submit(function() {
        var url;
        if ($('#btn_bookmark').hasClass('bookmarked'))
            url = '/trips/' + $('#trip_id').attr('value') + '/delete_bookmark/';
        else
            url = '/trips/' + $('#trip_id').attr('value') + '/bookmark/';
        $('#btn_bookmark').css('opacity', 0.3);
        $.ajax({
            url: url,
            success: function(html){
                if ($('#btn_bookmark').hasClass('bookmarked')) {
                    $('#btn_bookmark').removeClass('bookmarked');
                    $('#btn_bookmark').attr('value', '+收藏');
                } else {
                    $('#btn_bookmark').addClass('bookmarked');
                    $('#btn_bookmark').attr('value', '已收藏');
                }
                $('#btn_bookmark').css('opacity', 1);
            }
        });
        return false;
    });
});

$(document).ready(function(){
    if ($.browser.msie) {
        var maxWidth = 738;
        var photos = $('img.photo');
        for (var i = 0; i < photos.length; i++)
            if ($(photos[i]).width() > maxWidth)
                $(photos[i]).width(maxWidth);
    }

    if ($('#map_data').children('[class!="track"]').length <= 1)
        $('#map_controller a.right').css('opacity', 0.3);

    $('#map_controller a.right').click(move_to_next);
    $('#map_controller a.left').click(move_to_prev);
    $('#map_popup a.right').live('click', move_to_next);
    $('#map_popup a.left').live('click', move_to_prev);

    $('div.trip_item').mouseenter(function() {
        $(this).children('div.stats_wrapper').children('div.item_actions').fadeIn('fast');
    });

    $('div.trip_item').mouseleave(function() {
        $(this).children('div.stats_wrapper').children('div.item_actions').fadeOut('fast');
    });

    $('div.item_actions a.delete').click(function() {
        if(confirm('确定要删除此条吗？') == false)
            return false;

        var trip_item = $(this).parents('div.trip_item');
        trip_item.css('opacity', 0.3);
        $.ajax({
            url: $(this).attr('href'),
            type: 'DELETE',
            success: function(msg){
                msg = eval(msg);
                if (msg.error)
                    alert(msg.error);
                else
                    trip_item.slideUp('slow', function() {
                        trip_item.remove();
                    });
            }
        });
        return false;
    });

    $("img.photo").show().lazyload({
        effect: "fadeIn"
    });

});
